C++ websocket 客户端搭建

您所在的位置:网站首页 websocket++ 教程 C++ websocket 客户端搭建

C++ websocket 客户端搭建

2023-03-19 15:39| 来源: 网络整理| 查看: 265

话不多说,用的是websocket++,应该是目前用户最多的一个c++关于websocket的库,实际开发中也较稳定

针对官网提供的代码做了一点点修改,可以实现收发功能

#include #include #include #include "json.h" using namespace std; typedef websocketpp::client client; using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; using json = nlohmann::json; static bool is_connect = false; client c; client::connection_ptr con; // pull out the type of messages sent by our config typedef websocketpp::config::asio_client::message_type::ptr message_ptr; // Handlers void on_open(client* c, websocketpp::connection_hdl hdl) { is_connect = true; } void on_fail(client* c, websocketpp::connection_hdl hdl) { c->get_alog().write(websocketpp::log::alevel::app, "Connection Failed"); } void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg) { c->get_alog().write(websocketpp::log::alevel::app, "Received Reply: "+msg->get_payload()); } void on_close(client* c, websocketpp::connection_hdl hdl) { c->get_alog().write(websocketpp::log::alevel::app, "Connection Closed"); } void int_web(){ std::string uri = "ws://localhost:80"; try { // set logging policy if needed c.clear_access_channels(websocketpp::log::alevel::frame_header); c.clear_access_channels(websocketpp::log::alevel::frame_payload); //c.set_error_channels(websocketpp::log::elevel::none); // Initialize ASIO c.init_asio(); // Register our handlers c.set_open_handler(bind(&on_open,&c,::_1)); c.set_fail_handler(bind(&on_fail,&c,::_1)); c.set_message_handler(bind(&on_message,&c,::_1,::_2)); c.set_close_handler(bind(&on_close,&c,::_1)); // Create a connection to the given URI and queue it for connection once // the event loop starts websocketpp::lib::error_code ec; con = c.get_connection(uri, ec); //添加子协议 con->add_subprotocol("subprotocol",ec); c.connect(con); // Start the ASIO io_service run loop c.run(); } catch (const std::exception & e) { std::cout


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3